package com.btex.app;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.security.rp.RPSDK;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.taobao.windvane.config.GlobalConfig.context;

public class CertificationOneActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_menu)
    TextView mTvMenu;
    @BindView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R.id.activity_certfitction_one_ed_name)
    EditText mActivityCertfitctionOneEdName;
    @BindView(R.id.activity_certfitction_one_ed_number)
    EditText mActivityCertfitctionOneEdNumber;
    @BindView(R.id.activity_certfitction_one_tv_go)
    TextView mActivityCertfitctionOneTvGo;
    @BindView(R.id.activity_certfitction_one_spinner)
    Spinner mActivityCertfitctionOneSpinner;
    private ArrayList<String> mStrings;

    public String type = "1";
    private MicroAVLIDialog mMicroAVLIDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_certification_one);
        ButterKnife.bind(this);

        mMicroAVLIDialog = new MicroAVLIDialog(this);

        initSpinner();

        mTvTitle.setText("C1认证");
    }

    private void initSpinner() {
        mStrings = new ArrayList<>();
        mStrings.add("身份证");
        mStrings.add("军官证");
        mStrings.add("护照");
        String[] string = mStrings.toArray(new String[mStrings.size()]);
        //将可选内容与ArrayAdapter连接起来
        ArrayAdapter<String> adapter = new ArrayAdapter<>(CertificationOneActivity.this, R.layout.my_spinner, string);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mActivityCertfitctionOneSpinner.setAdapter(adapter);
        mActivityCertfitctionOneSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
                    type = "1";
                } else if (position == 1) {
                    type = "2";
                } else {
                    type = "3";
                }


                Log.i("kjwndqwdoiqwo", type);


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.iv_back, R.id.activity_certfitction_one_tv_go})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:

                finish();

                break;
            case R.id.activity_certfitction_one_tv_go:


                if (TextUtils.isEmpty(mActivityCertfitctionOneEdName.getText().toString().trim())) {
//                    Snackbar snackbar = Util.ShortSnackbar(mActivityCertfitctionOneEdName, "姓名不能为空", Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                    snackbar.show();
                    Util.showSnachBar(this, getResources().getColor(R.color.red), "姓名不能为空");
                    return;
                }

                if (TextUtils.isEmpty(mActivityCertfitctionOneEdNumber.getText().toString().trim())) {
//                    Snackbar snackbar = Util.ShortSnackbar(mActivityCertfitctionOneEdName, "证件号不能为空", Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                    snackbar.show();

                    Util.showSnachBar(this, getResources().getColor(R.color.red), "证件号不能为空");
                    return;
                }

                goCertification();
                break;
        }
    }

    private void goCertification() {

        mMicroAVLIDialog.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(this);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(context, sp);
        RequestParams params = new RequestParams();
        params.addBodyParameter("true_name", mActivityCertfitctionOneEdName.getText().toString().trim());
        params.addBodyParameter("type", type);
        params.addBodyParameter("no", mActivityCertfitctionOneEdNumber.getText().toString().trim());
//        params.addBodyParameter("no", mActivityCertfitctionOneEdNumber.getText().toString().trim());
        params.addHeader("my-client", "android");


        OkGo.<String>post(Config.SET_IDCARD).params("true_name", mActivityCertfitctionOneEdName.getText().toString().trim())
                .params("type", type)
                .params("no", mActivityCertfitctionOneEdNumber.getText().toString().trim())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        mMicroAVLIDialog.dismiss();
                        String result = response.body();
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {

                                EventBus.getDefault().post("CertificationOneActivityone");
                                getData();

                            } else {
                                Util.showSnachBar(CertificationOneActivity.this, getResources().getColor(R.color.red), new JSONObject(result).getString("info"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                    }
                });

//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.SET_IDCARD, params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//
//                mMicroAVLIDialog.dismiss();
//                String result = responseInfo.result;
//                Log.i("kjwdnqkwjndqkwjdnq", responseInfo.result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//
//                        EventBus.getDefault().post("CertificationOneActivityone");
//
//                        getData();
//
//                    } else {
////                        Snackbar snackbar = Util.ShortSnackbar(mActivityCertfitctionOneEdName, new JSONObject(result).getString("info"), Color.parseColor("#ffffff"), Color.parseColor("#272736"));
////                        snackbar.show();
//
//                        Util.showSnachBar(CertificationOneActivity.this, getResources().getColor(R.color.red), new JSONObject(result).getString("info"));
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//
//            }
//        });
    }


    private void getData() {
        mMicroAVLIDialog.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(context);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(context, sp);
        int num = (int) ((Math.random() * 9 + 1) * 100000);


        OkGo.<String>get(Config.GET_CHECKRP_TOKEN + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                mMicroAVLIDialog.dismiss();
                String result = response.body();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        SharedPreferencesUtil.getSharedPreferences(CertificationOneActivity.this).putString("prove_level", "C1");
                        String data = jsonObject.getString("data");
                        toAliyun(data);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });


//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_CHECKRP_TOKEN + "?rnd=" + String.valueOf(num), new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                mMicroAVLIDialog.dismiss();
//                String result = responseInfo.result;
//                Log.i("kjwdnqkwjndqkwjdnq", responseInfo.result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                        SharedPreferencesUtil.getSharedPreferences(CertificationOneActivity.this).putString("prove_level", "C1");
//                        String data = jsonObject.getString("data");
//                        toAliyun(data);
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//
//            }
//        });
    }

    private void toAliyun(String token) {


        RPSDK.start(token, context,
                new RPSDK.RPCompletedListener() {
                    @Override
                    public void onAuditResult(RPSDK.AUDIT audit) {


                        if (audit == RPSDK.AUDIT.AUDIT_PASS) {
                            //认证通过
                            EventBus.getDefault().post("AuthenticationInformationAcitvity");
                            finish();
                            SharedPreferencesUtil.getSharedPreferences(CertificationOneActivity.this).putString("prove_level", "C2");
                        } else if (audit == RPSDK.AUDIT.AUDIT_FAIL) {
                            //认证不通过

                        } else if (audit == RPSDK.AUDIT.AUDIT_IN_AUDIT) {
                            //认证中，通常不会出现，只有在认证审核系统内部出现超时，未在限定时间内返回认证结果时出现。此时提示用户系统处理中，稍后查看认证结果即可。

                        } else if (audit == RPSDK.AUDIT.AUDIT_NOT) {
                            //未

                        } else if (audit == RPSDK.AUDIT.AUDIT_EXCEPTION) {
                            //系统异常
//                            Snackbar snackbar = Util.ShortSnackbar(mActivityCertfitctionOneEdName, "系统异常", Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                            snackbar.show();
                            Util.showSnachBar(CertificationOneActivity.this, getResources().getColor(R.color.red), "系统异常");
                        }
                    }
                });
    }

}
